//
//  JPApiDefaultService.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/4/20.
//

#import "JPApiDefaultService.h"
#import <AFNetworking/AFHTTPSessionManager.h>
#import "JPNetworking.h"

@interface JPApiDefaultService ()

@property (nonatomic, strong) AFHTTPRequestSerializer *httpRequestSerializer;

@end

@implementation JPApiDefaultService


#pragma mark - public methods
- (NSURLRequest *)requestWithParams:(NSDictionary *)params methodName:(NSString *)methodName requestType:(JPAPIManagerRequestType)requestType{
  
    NSString *_method;
    NSString *_urlString;
    NSDictionary *_params;
    
  
    switch (requestType) {
        case JPAPIManagerRequestTypeGET:{
            _method = @"GET";
            _urlString = [NSString stringWithFormat:@"%@%@", self.baseURL, methodName];
            _params = params;
            break;
        }
            
        case JPAPIManagerRequestTypePOST:{
            _method = @"POST";
            _urlString = [NSString stringWithFormat:@"%@%@", self.baseURL, methodName];
            _params = params;
            break;
        }
        case JPAPIManagerRequestTypePOSTFile:{
            _method = @"POST";
            _urlString = [NSString stringWithFormat:@"%@%@", self.baseURL, methodName];
            _params = nil;
            break;
        }
        case JPAPIManagerRequestTypeAppendGET:{
            _method = @"GET";
            if (params.allValues.count){
                _urlString = [NSString stringWithFormat:@"%@%@%@", self.baseURL, methodName,[params.allValues componentsJoinedByString:@"/"]];
            }else{
                _urlString = [NSString stringWithFormat:@"%@%@", self.baseURL, methodName];
            }
            _params = @{};
            break;
        }
        case JPAPIManagerRequestTypeAppendPOST:{
            _method = @"POST";
            if (params.allValues.count){
                _urlString = [NSString stringWithFormat:@"%@%@%@", self.baseURL, methodName,[params.allValues componentsJoinedByString:@"/"]];
            }else{
                _urlString = [NSString stringWithFormat:@"%@%@", self.baseURL, methodName];
            }
            _params = @{};
            break;
        }
        case JPAPIManagerRequestTypeAppendParameterPOST:{
            _method = @"POST";
            if (params.allValues.count){
                NSMutableString *urlstr = [NSMutableString string];
                for (NSInteger i = 0; i < params.allKeys.count; i++) {
                    if (i == 0) {
                        [urlstr appendString:[NSString stringWithFormat:@"?%@=%@",params.allKeys[i],params.allValues[i]]];
                    }else{
                        [urlstr appendString:[NSString stringWithFormat:@"&%@=%@",params.allKeys[i],params.allValues[i]]];
                    }
                }
                _urlString = [NSString stringWithFormat:@"%@%@%@", self.baseURL,methodName,urlstr];
            }else{
                _urlString = [NSString stringWithFormat:@"%@%@", self.baseURL, methodName];
            }
            _params = @{};
            break;
        }
        case JPAPIManagerRequestTypeDELETE:{
            _method = @"DELETE";
            if (params.allValues.count){
                NSMutableString *urlstr = [NSMutableString string];
                for (NSInteger i = 0; i < params.allKeys.count; i++) {
                    if (i == 0) {
                        [urlstr appendString:[NSString stringWithFormat:@"?%@=%@",params.allKeys[i],params.allValues[i]]];
                    }else{
                        [urlstr appendString:[NSString stringWithFormat:@"&%@=%@",params.allKeys[i],params.allValues[i]]];
                    }
                }
                _urlString = [NSString stringWithFormat:@"%@%@%@", self.baseURL,methodName,urlstr];
            }else{
                _urlString = [NSString stringWithFormat:@"%@%@", self.baseURL, methodName];
            }
            _params = @{};
            break;
        }
        default:
            break;
    }
    
    //添加Header
    if(!([methodName isEqualToString:@"/sms/code/send"]||[methodName isEqualToString:@"/system/areaCode/list"])){
        NSString *access_token = [[NSUserDefaults standardUserDefaults]objectForKey:@"access_token"];
        if(access_token){
            [self.httpRequestSerializer setValue:access_token forHTTPHeaderField:@"Authorization"];
        }else{
            [self.httpRequestSerializer setValue:nil forHTTPHeaderField:@"Authorization"];
        }
    }else{
        [self.httpRequestSerializer setValue:nil forHTTPHeaderField:@"Authorization"];
    }
    
    NSMutableURLRequest *request;
    if (requestType == JPAPIManagerRequestTypePOSTFile) {
        //图片上传
        NSMutableDictionary *dict = params.mutableCopy;
        NSURL *file;
        for (NSString *key in params.allKeys) {
            if ([params[key] isKindOfClass:[NSURL class]]) {
                file = params[key];
                [dict removeObjectForKey:key];
            }
        }
        request = [self.httpRequestSerializer multipartFormRequestWithMethod:_method
                                                         URLString:_urlString
                                                        parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                                                                 [formData appendPartWithFileURL:file name:@"file" error:nil];
                                                  
                                                        } error:nil];
    }else{
        request = [self.httpRequestSerializer requestWithMethod:_method
                                                      URLString:_urlString
                                                     parameters:_params
                                                          error:nil];
    }

    return request;
}

-(NSString *)URLEncodedString:(NSString *)str{

    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}

- (NSDictionary *)resultWithResponseData:(NSData *)responseData response:(NSURLResponse *)response request:(NSURLRequest *)request error:(NSError **)error{
    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    if([responseData isKindOfClass:[NSDictionary class]]){
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:responseData options:0 error:nil];
        result[kJPApiProxyValidateResultKeyResponseData] = data;
        result[kJPApiProxyValidateResultKeyResponseJSONString] = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
     
    if([responseData isKindOfClass:[NSString class]]){
        result[kJPApiProxyValidateResultKeyResponseData] = responseData;
    }
    if([responseData isKindOfClass:[NSString class]]){
        result[kJPApiProxyValidateResultKeyResponseJSONString] = responseData;
    }
    if([responseData isKindOfClass:[NSDictionary class]]){
        result[kJPApiProxyValidateResultKeyResponseJSONObject] = responseData;
    }
    return result;
}

#pragma mark - getters and setters
- (NSString *)baseURL{
    return @"https://www.riyudao.com:8080/api";
}

- (AFHTTPRequestSerializer *)httpRequestSerializer{
    if (_httpRequestSerializer == nil) {
        AFJSONRequestSerializer *httpRequestSerializer = [AFJSONRequestSerializer serializer];
        httpRequestSerializer.timeoutInterval = 20.0;
        _httpRequestSerializer = httpRequestSerializer;
    }
    return _httpRequestSerializer;
}


@end
